<?php

namespace App\Http\Controllers\Export;

use App\Http\Controllers\Admin\CommonController;
use App\Http\Controllers\Controller;
use App\Models\AnswerActivity;
use App\Models\AnswerActivityProblem;
use App\Models\AnswerActivityUnit;
use App\Models\UserAddress;
use App\Models\UserInfo;
use App\Validate\AnswerActivityProblemValidate;
use Illuminate\Support\Facades\Cache;
use Maatwebsite\Excel\Facades\Excel;


/**
 * excel导出导入功能 
 */
class AnswerActivityProblemExport extends Controller
{

    public $model = null;
    public $activityModel = null;
    public $validate = null;
    public function __construct()
    {
        parent::__construct();

        $this->model = new AnswerActivityProblem();
        $this->activityModel = new AnswerActivity();
        $this->validate = new AnswerActivityProblemValidate();

    } 

    /**
     * 活动题库导出
     * @param act_id int 活动id
     * @param unit_id int 单位id  
     * @param state int 1正常 2被禁用
     * @param is_show_analysis int 是否显示解析  1、显示 2、不显示
     * @param start_time datetime 创建时间范围搜索(开始) 
     * @param end_time datetime 创建时间范围搜索(结束) 
     * @param keywords string 搜索关键词(题目)
     */
    public function index()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $keywords = $this->request->keywords;
        $unit_id = $this->request->unit_id;
        $state = $this->request->state;
        $is_show_analysis = $this->request->is_show_analysis;
        $act_id = $this->request->act_id;

        $res = $this->model->lists($act_id, $keywords, $unit_id, $state, $is_show_analysis, $start_time, $end_time, 1, 99999);

        if ($res['total'] == 0 || !$res['data']) {
            $res['data'] = [];
        }

        $node = $this->activityModel->where('id', $act_id)->value('node');
        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['unit_name'] = !empty($val['con_unit']['name']) ?  $val['con_unit']['name'] : config('other.unit_name');

            unset($res['data'][$key]['con_unit']);
        }

        $row[0]["id"] = '序号';
        if ($node != 1) $row[0]["name"] = '所属单位';
        $row[0]["title"] = '题目';
        $row[0]["img"] = '图片';
        $row[0]["type"] = '题目类型';
        $row[0]["success_answer"] = '正确答题';
        $row[0]["answer1"] = '答题1';
        $row[0]["answer2"] = '答题2';
        $row[0]["answer3"] = '答题3';
        $row[0]["answer4"] = '答题4';
        $row[0]["answer5"] = '答题5';
        $row[0]["is_show_analysis"] = '是否显示解析';
        $row[0]["analysis"] = '解析';
        $row[0]["state"] = '状态';
        $row[0]["create_time"] = '创建时间';

        $title = '题库列表-' . date('YmdHis');

        list($data , $img) = $this->setData($res['data'], $node); //要导入的数据

        return $this->exportData($data, $title, $row ,$img ,$node);
    }


    
    /**
     * 活动题库模板导出
     * @param act_id int 活动id
     */
    public function template()
    {

        $act_id = $this->request->act_id;
        if (empty($act_id)) {
            return $this->returnApi(201, "活动id不能为空");
        }
        $node = $this->activityModel->where('id', $act_id)->value('node');

        //设置表头
        $row[0]["id"] = '序号';
        if ($node != 1) $row[0]["name"] = '所属单位';
        $row[0]["title"] = '题目';
        $row[0]["img"] = '图片';
        $row[0]["type"] = '题目类型（选择、填空二选一）';
        $row[0]["success_answer"] = '正确答题（必须与选项内容一致）';
        $row[0]["answer1"] = '答题1（若是填空题，答案1就等于正确答案）';
        $row[0]["answer2"] = '答题2';
        $row[0]["answer3"] = '答题3';
        $row[0]["answer4"] = '答题4';
        $row[0]["answer5"] = '答题5';
        $row[0]["is_show_analysis"] = '是否显示解析（是、否二选一）';
        $row[0]["analysis"] = '解析';


        
        //设置表头
        $data[0]["id"] = '1';
        if ($node != 1) $data[0]["name"] = 'XXX图书馆';
        $data[0]["title"] = '劳动节是每年的____。';
        $data[0]["img"] = '';
        $data[0]["type"] = '选择题';
        $data[0]["success_answer"] = '5月1日';
        $data[0]["answer1"] = '5月1日';
        $data[0]["answer2"] = '4月1日';
        $data[0]["answer3"] = '6月1日';
        $data[0]["answer4"] = '';
        $data[0]["answer5"] = '';
        $data[0]["is_show_analysis"] = '否';
        $data[0]["analysis"] = '';


        $file_name = '活动题库模板导出';
        //执行导出
        $header = $row; //导出表头
        $excel = new Export($data, $header, $file_name);
        $excel->setColumnWidth(['A' => 10, 'B' => 20, 'C' => 30, 'D' => 20, 'E' => 30, 'F' => 20, 'G' => 20, 'H' => 20, 'I' => 20, 'J' => 20, 'K' => 20, 'L' => 20, 'M' => 20, 'N' => 20, 'O' => 30]);
        $excel->setRowHeight([1 => 30]);

        return Excel::download($excel, $file_name . '.xlsx');
    }


    /**
     * 导出数据
     *
     * @param [type] $data
     * @return void
     */
    public function exportData($data, $title, $row ,$img , $node)
    {
        $header = $row; //导出表头
        $excel = new Export($data, $header, $title);
        $excel->setColumnWidth(['A' => 10, 'B' => 15, 'C' => 20, 'D' => 20, 'E' => 20, 'F' => 20, 'G' => 20, 'H' => 25, 'I' => 25, 'J' => 20, 'K' => 20, 'L' => 20, 'M' => 20, 'N' => 20, 'O' => 30]);
        $excel->setRowHeight(30 , count($data) + 1);
        $imgPosition = $node != 1 ? 'D' : 'C';
        $excel->setExcelImg($img , $imgPosition , 40,40);
        // $excel->setFreezePane('A2');
        // $excel->setFont(['A1:Z1265' => '宋体']);
        // $excel->setFontSize(['A1:I1' => 14,'A2:Z1265' => 10]);
        // $excel->setBold(['A1:Z2' => true]);
        // $excel->setBackground(['A1:A1' => '808080','C1:C1' => '708080']);
        // $excel->setMergeCells(['A1:I1']);
        // $excel->setBorders(['A2:D5' => '#000000']);
        return Excel::download($excel, $title . '.xlsx');
    }


    /**
     * 处理 终端书籍列表 数据
     */
    public function setData($data, $node)
    {
        $excel_data = [];
        $excel_img = [];
        /*设置excel内容*/
        foreach ($data as $key => $val) {
            //图片资源
            $excel_img[] = $val['img'];

            $excel_data[$key]['id'] = $key + 1;
            if ($node != 1) {
                $excel_data[$key]["name"] = $val['unit_name'];
            }
            $excel_data[$key]["title"] = $val["title"];
            $excel_data[$key]["img"] = '';
            $excel_data[$key]["type"] = $val['type'] == 1 ? '选择题' : '填空题';
            $excel_data[$key]["success_answer"] = $val["success_answer"];
            for($i = 1 ; $i < 6 ; $i++){
                $excel_data[$key]["answer".$i] = !empty($val["con_answer"][$i-1]) ? $val["con_answer"][$i-1]['content'] : '';
            }
            $excel_data[$key]["is_show_analysis"] = $val["is_show_analysis"] == 1 ? '显示' : '不显示';
            $excel_data[$key]["analysis"] = $val["analysis"];
            $excel_data[$key]["state"] = $val["state"] == 1 ? '正常' : '禁用';
            $excel_data[$key]["create_time"] = $val["create_time"];
        }
        return [$excel_data , $excel_img];
    }
}
